package org.pombo.sqm;

import org.pombo.gtm.Action;
import org.pombo.gtm.InformationSet;
import org.pombo.gtm.StrategyNode;

class OpponentNodeWorstPayoffCalculator implements NodeWorstPayoffCalculator<StrategyNode> {

	private StrategyNode node;
	private NodeProbabilities nodeProbabilities;
	private WorstPayoffCalculatorFactory calculate;

	OpponentNodeWorstPayoffCalculator(WorstPayoffCalculatorFactory worstPayoffCalcFactory, NodeProbabilities nodeProbabilities) {
		this.calculate = worstPayoffCalcFactory;
		this.nodeProbabilities = nodeProbabilities;
	}

	public void setNode(StrategyNode node) {
		this.node = node;
	}

	public double worstPayoff() {
		Action bestAction = this.worstPayoffAction(this.node.getInformationSet());
		return this.calculate.on(this.node.getNodeForAction(bestAction)).worstPayoff();
	}

	private Action worstPayoffAction(InformationSet infoSet) {
		Action worstAction = null;
		double worstAveragePayoff = Double.POSITIVE_INFINITY;
		for (Action action : infoSet.getActions()) {
			double averagePayoff = 0;
			for (StrategyNode playerNode : infoSet.getNodes()) {
				averagePayoff += this.getNodeProbability(playerNode)
							* this.calculate.on(playerNode.getNodeForAction(action)).worstPayoff();
			}
			if (averagePayoff < worstAveragePayoff) {
				worstAction = action;
				worstAveragePayoff = averagePayoff;
			}
		}
		return worstAction;
	}

	private double getNodeProbability(StrategyNode playerNode) {
		return this.nodeProbabilities.getProbability(playerNode);
	}
}
